package com.khyr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.khyr.dao.*;
import com.khyr.entity.*;
import com.khyr.feign.MedicinesFeign;
import com.khyr.service.NewCareService;
import com.khyr.utils.SnowflakeIdGenerator;
import com.khyr.vo.GetPatientAllMessageByPatientIdDto;
import com.khyr.vo.HisCareHVo;
import com.khyr.vo.R;
import com.khyr.vo.SaveCareOrderItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：Zhang
 * @date ：Created in 2025/3/14 15:40
 * @description：新开就诊
 * @modified By：
 * @version: 1.0
 */
@Service
public class NewCareServiceImpl implements NewCareService {
    @Autowired
    private MedicinesFeign medicines;
    @Autowired
    private CareOrderItemDao careOrderItemDao;
    @Autowired
    private CareOrderDao careOrderDao;
    @Autowired
    private DeptDao deptDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private HisRegistrationDao hisRegistrationDao;
    @Autowired
    private HisPatientDao hisPatientDao;
    @Autowired
    private HisPatientFileDao hisPatientFileDao;
    @Autowired
    private HisCareHistoryDao hisCareHistoryDao;
    /**
     * @create by: Zr
     * @description: 待就诊
     * @create time: 2025/3/14 15:58
     * @param scheudlingType
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HisRegistration>>
     */
    @Override
    public R<List<HisRegistration>> queryToBeSeenRegistration(Long uId,String scheudlingType) {
        QueryWrapper<HisRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheduling_type",scheudlingType);
        // 根据医生id查询以及查询医生id为空的数据
        queryWrapper.nested(wrapper ->
                wrapper.eq("user_id", uId)
                        .or()
                        .isNull("user_id")
        );
        // 待就诊
        queryWrapper.eq("registration_status","1");
        // 时间必须在今日时间后(日期格式为yyyy-MM-ss)
        queryWrapper.ge("visit_date", LocalDate.now());
        List<HisRegistration> hisRegistrationList = hisRegistrationDao.selectList(queryWrapper);
        return new R<>(200,"查询成功",hisRegistrationList);
    }
    /**
     * @create by: Zr
     * @description: 查询所有就诊中的挂号信息
     * @create time: 2025/3/14 16:11
     * @param scheudlingType
     * @param uId
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HisRegistration>>
     */
    @Override
    public R<List<HisRegistration>> queryVisitingRegistration(String scheudlingType, Long uId) {
        QueryWrapper<HisRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheduling_type",scheudlingType);
        // 待就诊
        queryWrapper.eq("registration_status","2");
        queryWrapper.eq("user_id",uId);
        List<HisRegistration> hisRegistrationList = hisRegistrationDao.selectList(queryWrapper);
        return new R<>(200,"查询成功",hisRegistrationList);
    }
    /**
     * @create by: Zr
     * @description: 就诊完成
     * @create time: 2025/3/14 16:13
     * @param scheudlingType
     * @param uId
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HisRegistration>>
     */
    @Override
    public R<List<HisRegistration>> queryVisitCompletedRegistration(String scheudlingType, Long uId) {
        QueryWrapper<HisRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheduling_type",scheudlingType);
        // 待就诊
        queryWrapper.eq("registration_status","3");
        queryWrapper.eq("user_id",uId);
        // 时间必须在今日时间后(日期格式为yyyy-MM-ss)
        List<HisRegistration> hisRegistrationList = hisRegistrationDao.selectList(queryWrapper);
        return new R<>(200,"查询成功",hisRegistrationList);
    }
    /**
     * @create by: Zr
     * @description: 根据挂号流水编号，更改挂号单状态，并存入医生信息
     * @create time: 2025/3/14 16:23
     * @param regId
     * @return com.khyr.vo.R<java.lang.String>
     */
    @Override
    public R<String> receivePatient(String regId, Long uId, String name) {
        // 根据挂号流水编号，更改挂号单状态，并存入医生信息
        QueryWrapper<HisRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("registration_id",regId);

        HisRegistration hisRegistration = hisRegistrationDao.selectOne(queryWrapper);
        if(hisRegistration!=null){
            hisRegistration.setRegistrationStatus("2");
            hisRegistration.setUserId(uId);
            hisRegistration.setDoctorName(name);
            hisRegistrationDao.update(hisRegistration,queryWrapper);
            return new R<>(200,"操作成功",null);
        }
        else {
            return new R<>(400,"操作失败",null);
        }
    }
    /**
     * @create by: Zr
     * @description: 根据患者id查询患者信息，档案，病例
     * @create time: 2025/3/14 16:47
     * @param patientId
     * @return com.khyr.vo.R<com.khyr.vo.GetPatientAllMessageByPatientIdDto>
     */
    @Override
    public R<GetPatientAllMessageByPatientIdDto> getPatientAllMessageByPatientId(String patientId) {
        // 根据患者id查询患者信息，档案，病例
        QueryWrapper<HisPatient> queryWrapper = new QueryWrapper<>();
        GetPatientAllMessageByPatientIdDto getPatientAllMessageByPatientIdDto =
                new GetPatientAllMessageByPatientIdDto();
        queryWrapper.eq("patient_id",patientId);
        HisPatient hisPatient = hisPatientDao.selectOne(queryWrapper);
        if (hisPatient!=null){
            getPatientAllMessageByPatientIdDto.setPatient(hisPatient);
        }
        // 查询患者档案
        QueryWrapper<HisPatientFile> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("patient_id",patientId);
        HisPatientFile hisPatientFileList = hisPatientFileDao.selectOne(queryWrapper1);
        getPatientAllMessageByPatientIdDto.setPatientFile(hisPatientFileList);
        // 查询患者病例
        QueryWrapper<HisCareHistory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("patient_id",patientId);
        List<HisCareHistory> careHistoryList = hisCareHistoryDao.selectList(queryWrapper2);
        getPatientAllMessageByPatientIdDto.setCareHistoryList(careHistoryList);

        return new R<>(200,"查询成功",getPatientAllMessageByPatientIdDto);
    }
    /**
     * @create by: Zr
     * @description: 根据挂号单查询病例信息
     * @create time: 2025/3/14 17:06
     * @param regId
     * @return com.khyr.vo.R<com.khyr.entity.HisCareHistory>
     */
    @Override
    public R<HisCareHistory> getCareHistoryByRegId(String regId) {
        QueryWrapper<HisCareHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reg_id",regId);
        return new R<>(200,"查询成功",hisCareHistoryDao.selectOne(queryWrapper));
    }
    /**
     * @create by: Zr
     * @description: 保存病例信息，需要查找医生信息和部门信息
     * @create time: 2025/3/17 9:31
     * @param careHistory
     * @param uId
     * @return com.khyr.vo.R<com.khyr.entity.HisCareHistory>
     */
    @Override
    public R<HisCareHistory> saveCareHistory(HisCareHVo careHistory, Long uId) {

        // 获取当前接诊的医生信息及科室信息
        User user = getUserByUserId(uId);
        // 部门信息
        QueryWrapper<Dept> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("dept_id",user.getDeptId());
        Dept dept = deptDao.selectOne(queryWrapper1);
        // 定义目标格式：yyyy-MM-dd HH:mm:ss
        DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .withZone(ZoneId.of("Asia/Shanghai"));
        String formattedDateTime = null;
        if(careHistory.getCaseDateObj()!=null){
            String isoDateTime = careHistory.getCaseDateObj();
            Instant instant = Instant.parse(isoDateTime);
            // 将 Instant 格式化为目标格式的字符串
            formattedDateTime = targetFormatter.format(instant);
        }else {
            formattedDateTime = LocalDateTime.now().format(targetFormatter);
        }

//        String chId = "CH" + SnowflakeIdGenerator.nextId();
//        careHistory.setChId(chId);

        // 将 careHistory 赋给新建的 HisCareHistory 对象
        HisCareHistory hisCareHistory = new HisCareHistory();
        BeanUtils.copyProperties(careHistory, hisCareHistory);

        // 将 formattedDateTime 转换为 Date
        LocalDateTime localDateTimeObj = LocalDateTime.parse(formattedDateTime, targetFormatter);
        Date date = Date.from(localDateTimeObj.atZone(ZoneId.of("Asia/Shanghai")).toInstant());

        // 设置 Date 类型的 careTime
        hisCareHistory.setCareTime(date);
        hisCareHistory.setUserId(user.getUserId());
        hisCareHistory.setUserName(user.getUserName());
        hisCareHistory.setDeptId(user.getDeptId());
        hisCareHistory.setDeptName(dept.getDeptName());

        // 判断 regId 是否存在
        QueryWrapper<HisCareHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reg_id", careHistory.getRegId());
        HisCareHistory existingHistory = hisCareHistoryDao.selectOne(queryWrapper);
        if (existingHistory != null) {
            // 如果存在，进行更新操作
            hisCareHistory.setChId(existingHistory.getChId()); // 保持原有的 chId
            int updateResult = hisCareHistoryDao.updateById(hisCareHistory);
            if(updateResult == 1) {
                return new R<>(200, "更新成功", hisCareHistory);
            } else {
                return new R<>(400, "更新失败", hisCareHistory);
            }
        } else {
            // 如果不存在，进行新增操作
            String chId = "CH" + SnowflakeIdGenerator.nextId();
            hisCareHistory.setChId(chId);
            int insertResult = hisCareHistoryDao.insert(hisCareHistory);
            if(insertResult == 1) {
                return new R<>(200, "添加成功", hisCareHistory);
            } else {
                return new R<>(400, "添加失败", hisCareHistory);
            }
        }


    }
    /**
     * @create by: Zr
     * @description: 根据病例ID查询处方列表及详情
     * @create time: 2025/3/17 10:51
     * @param chId
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HisCareHistory>>
     */
    @Override
    public R<List<SaveCareOrderItemVo>> queryCareOrdersByChId(String chId) {
        List<SaveCareOrderItemVo> saveCareOrderItemDto = new ArrayList<>();
        // 根据chId查询coId
        QueryWrapper<CareOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ch_id",chId);
        List<CareOrder> careOrders = careOrderDao.selectList(queryWrapper);
        // 根据coId查询careOrderItem，获得处方详细信息
        for (CareOrder careOrder : careOrders) {
            SaveCareOrderItemVo saveCareOrderItemDto1 = new SaveCareOrderItemVo();
            saveCareOrderItemDto1.setCareOrder(careOrder);
            QueryWrapper<CareOrderItem> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("co_id",careOrder.getCoId());
            List<CareOrderItem> careOrderItems = careOrderItemDao.selectList(queryWrapper1);
            saveCareOrderItemDto1.setCareOrderItems(careOrderItems);
            saveCareOrderItemDto.add(saveCareOrderItemDto1);
        }

        return new R<>(200,"查询成功",saveCareOrderItemDto);
    }
    /**
     * @create by: Zr
     * @description: 保存处方信息，并减少对应的药品库存
     * @create time: 2025/3/17 14:24
     * @param data
     * @param uId
     * @return com.khyr.vo.R<com.khyr.vo.SaveCareOrderItemVo>
     */
    @Override
    public R<SaveCareOrderItemVo> saveCareOrderItem(SaveCareOrderItemVo data, Long uId) {
        SaveCareOrderItemVo saveCareOrderItemDto = new SaveCareOrderItemVo();
        // 获取 careOrder 和 careOrderItems
        CareOrder careOrder = data.getCareOrder();
        List<CareOrderItem> careOrderItems = data.getCareOrderItems();
        // 获取当前医生信息
        User user = getUserByUserId(uId);
        // 生成 coId
        String coId = "CO"+SnowflakeIdGenerator.nextId();
        // 设置 coId
        careOrder.setCoId(coId);
        // 设置其他信息
        careOrder.setUserId(uId);
        careOrder.setCreateBy(user.getUserName());
        careOrder.setCreateTime(new Date());
        careOrder.setUpdateBy(user.getUserName());
        careOrder.setUpdateTime(new Date());
        saveCareOrderItemDto.setCareOrder(careOrder);
        // 存入处方表
        careOrderDao.insert(careOrder);
        for(CareOrderItem careOrderItem : careOrderItems){
            // 生成 coId
            String itemId = "ITEM"+SnowflakeIdGenerator.nextId();
            careOrderItem.setItemId(itemId);
            careOrderItem.setCoId(coId);
            careOrderItem.setStatus("0");
            careOrderItem.setCreateTime(new Date());
            saveCareOrderItemDto.setCareOrderItems(careOrderItems);
            careOrderItemDao.insert(careOrderItem);
        }
        // 减药品库存
//        if(data.getCareOrderItems()!=null){
//            for(CareOrderItem careOrderItem : careOrderItems){
//                if("0".equals(careOrderItem.getItemType())){
//                    medicines.reduce(careOrderItem.getItemName(),Integer.valueOf(String.valueOf(careOrderItem.getNum())));
//                }
//            }
//        }

        return new R<>(200,"操作成功",saveCareOrderItemDto);
    }
    /**
     * @create by: Zr
     * @description: 根据处方明细id-item_id删除处方明细，并将处方中的药品返回库存中
     * @create time: 2025/3/17 15:09
     * @param itemId
     * @return com.khyr.vo.R<java.lang.String>
     */
    @Override
    public R<String> deleteCareOrderItemById(String itemId) {
        Integer num = 0;
        // 根据itemId查询itemType，如果为0，则将药品返回库存中
        QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("item_id",itemId);
        CareOrderItem careOrderItem = careOrderItemDao.selectOne(queryWrapper);
        String integerPart = String.valueOf(careOrderItem.getNum()).split("\\.")[0];  // 使用正则表达式分割，取第一个部分
        int result = Integer.parseInt(integerPart);
        if("0".equals(careOrderItem.getItemType())){
            medicines.add(Long.valueOf(careOrderItem.getItemRefId()),
                    Integer.valueOf(result));
            num = careOrderItemDao.deleteById(itemId);
        }else {
            num = careOrderItemDao.deleteById(itemId);
        }
        return new R<>(200,"操作成功",num+"");
    }
    /**
     * @create by: Zr
     * @description: 根据挂号id将挂号单状态修改为完成
     * @create time: 2025/3/17 15:09
     * @param regId
     * @return com.khyr.vo.R<java.lang.String>
     */
    @Override
    public R<String> visitComplete(String regId) {
        QueryWrapper<HisRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("registration_id",regId);
        HisRegistration hisRegistration = hisRegistrationDao.selectOne(queryWrapper);
        hisRegistration.setRegistrationStatus("3");
        if(hisRegistrationDao.updateById(hisRegistration)==1){
            return new R<>(200,"操作成功",null);
        }
        else {
            return new R<>(400,"操作失败",null);
        }
    }

    public User getUserByUserId(Long userId) {
        // 根据 userId 查询医生信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return userDao.selectOne(queryWrapper);
    }

}
